package com.hxzy.controller.userinfo;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.entity.UserInfo;
import com.hxzy.service.UserInfoService;
import com.hxzy.service.impl.UserInfoServiceImpl;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/2 9:18
 */
@WebServlet(urlPatterns = "/json/update")
public class UpdateJsonServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setCharacterEncoding("UTF-8");
    try {
        UserInfo userInfo = super.CollectiongParameterToJSON(req, UserInfo.class);
        Set<String> validator = BeanValidatorUtil.validator(UserInfo.class, userInfo);
        if (validator.isEmpty()){
            String hashpw = BCrypt.hashpw(userInfo.getLoginPwd(), BCrypt.gensalt());
            userInfo.setLoginPwd(hashpw);
            UserInfoService service=new UserInfoServiceImpl();
            int update = service.update(userInfo);
            ResultAjax resultAjax;
            if (update>0){
                resultAjax= ResultAjax.success("更新成功");
            }else {
                resultAjax=ResultAjax.error("更新失败");
            }
            super.render(resp, JSONObject.toJSONString(resultAjax));
        }else {
            String next = validator.iterator().next();
            ResultAjax error = ResultAjax.error(next);
            super.render(resp, JSONObject.toJSONString(error));
        }
    }catch (Exception e){
        e.printStackTrace();
    }


    }
    private UserInfo getInputStreamToJavaBean(ServletInputStream inputStream) throws IOException {
        StringBuffer  stringBuffer=new StringBuffer();
        //把字节流(byte)转换成字符流(char)
        BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream) );
        String str="";
        while( (str=bufferedReader.readLine())!=null){
            stringBuffer.append(str);
        }

        String strInfo=stringBuffer.toString();
        //转换json转换成java
        UserInfo userInfo = JSONObject.parseObject(strInfo.trim(), UserInfo.class);
        return userInfo;
    }
}
